package space.panker916.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import space.panker916.annotation.LoginRequired;
import space.panker916.event.EventProducer;
import space.panker916.pojo.Comment;
import space.panker916.pojo.DiscussPost;
import space.panker916.pojo.Event;
import space.panker916.service.CommentService;
import space.panker916.service.DiscussPostService;
import space.panker916.utils.HostHolder;
import space.panker916.utils.RedisKeyUtil;

import java.util.Date;

import static space.panker916.utils.Constants.*;


@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/add/{discussPostId}")
    @LoginRequired
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        // 触发评论事件（也许可以写成一个 service方法来封装 ？？）
        Event event = new Event();
        event.setTopic(TOPIC_COMMENT);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(comment.getEntityType());
        event.setEntityId(comment.getEntityId());
        event.setData("postId", discussPostId);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(post.getUserId());
        } else event.setEntityUserId(comment.getUserId());
        eventProducer.fireEvent(event);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            // 触发发帖事件
            event = new Event();
            event.setUserId(comment.getUserId());
            event.setTopic(TOPIC_PUBLISH);
            event.setEntityType(ENTITY_TYPE_POST);
            event.setEntityId(discussPostId);

            eventProducer.fireEvent(event);
        }

        // 计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, discussPostId);

        return "redirect:/discuss/detail/" + discussPostId;
    }

}
